<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Models\Ad;
use Illuminate\Http\Request;
use App\Models\Article;
use App\Http\Resources\AdResource;

class AdController extends Controller
{

    public function index(Article $article)
    {
        $ads = AdResource::collection($article->ads);
        return $ads;
    }


    public function store(Request $request, Article $article, Ad $ad)
    {
//        return $request;
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $ad = $article->ads()->create($request->input());
        $ad->extra = ['price' => $request->price, 'time' => $request->time, 'mobile' => $request->mobile];
        $ad->save();
        return $this->message('发表成功', $ad->toArray());
    }

    public function show(Article $article, Ad $ad)
    {
        return new AdResource($ad);
    }


    public function update(Request $request, Article $article, Ad $ad)
    {
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $ad->update($request->input());
        $ad->extra = ['price' => $request->price, 'time' => $request->time, 'mobile' => $request->moblie];
        $ad->save();
        return $this->message('修改成功', $ad->toArray());
    }


    public function destroy(Article $article, Ad $ad)
    {
        $ad->delete();
        return $this->message('删除成功');
    }

    public function adList()
    {
        //仅显示2条

//        $ads = AdResource::collection(Ad::all()->take(2));
//        $ads = Ad::all()->take(2);
//        return $ads;

        return Ad::where('recommend', 1)->orderBy('id', 'desc')->take(2)->get();
    }
}
